<template>
	<a-modal :title="title" :width="1500" :visible="visible" :maskClosable="false" :confirmLoading="confirmLoading"
		@ok="handleSubmit" @cancel="handleCancel">
		<a-card :bordered="false">
			<div class="table-page-search-wrapper">
				<a-form layout="inline">
					<a-row :gutter="48">

						<a-col :md="8" :sm="24" v-if="false">
							<a-form-item label="订单ID">
								<a-input v-model="queryParam.orderId" placeholder="请输入订单ID" />
							</a-form-item>
						</a-col>
						<a-col :md="8" :sm="24">
							<a-form-item label="物料编号">
								<a-input v-model="queryParam.materialCode" placeholder="请输入物料编号" />
							</a-form-item>
						</a-col>
						<a-col :md="6" :sm="24">
							<a-form-item label="领用方">
								<a-select placeholder="全部" :default-value="null" v-model="queryParam.classGroupId">
									<a-select-option :values="item.classGroupId" v-for="item in teamList" :key="item.classGroupId">
										{{ item.name }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :md="8" :sm="24">
							<a-button type="primary" @click="table.refresh(true)">查询</a-button>
							<a-button
								@click="() => { queryParam.classGroupId = null; queryParam.materialCode = null; table.refresh(true) }">重置</a-button>
						</a-col>
						<a-col :md="2" :sm="24">
							<a-button type="danger" :loading="dwnLoading" @click="handleExport">导出</a-button>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="table-operator">
				<a-space>
					<a-button type="primary" @click="$refs.addForm.add(emsOrder, materialType)" icon="plus">新增</a-button>
					<a-button type="danger" :disabled="!selectedRowKeys.length" @click="handleRemove"
						v-if="hasPerm('emsOrderMaterial:deleteBatchBC')">删除
					</a-button>
				</a-space>
			</div>

			<s-table ref="table" size="default" :columns="columns" :data="getData" :alert="true" :showPagination="false"
				:row-selection="rowSelection" :rowKey="record => record.orderId + record.orderMaterialId">

				<template slot="number" slot-scope="text, record">
					<a-input-number v-model:value="editRecord.number" :min="0" style="width: 67px;"
						v-if="editRecord.orderId + editRecord.orderMaterialId === record.orderId + record.orderMaterialId" />

					<span v-else>{{ text }}</span>

				</template>

				<template slot="classGroupId" slot-scope="text, record">
					<a-select placeholder="全部" style="width: 100%" v-model="record.classGroupId">
						<a-select-option :values="item.classGroupId" v-for="item in teamList" :key="item.classGroupId">
							{{ item.name }}
						</a-select-option>
					</a-select>
					<!-- <span v-else>{{ text }}</span> -->

				</template>
				<template slot="normalNumber" slot-scope="text, record">
					<a-input-number v-model:value="record.normalNumber" :min="0"
						:max="record.number - record.completedNumber < 0 ? 0 : record.number - record.completedNumber"
						style="width: 67px;" :disabled="record.completedNumber >= record.number" />
				</template>

				<template slot="extraNumber" slot-scope="text, record">
					<a-input-number v-model:value="record.extraNumber" :min="0" style="width: 67px;"
						:disabled="record.completedNumber < record.number" />
				</template>

				<span slot="action" slot-scope="text, record">
					<a-space>
						<template v-if="hasPerm('emsOrderMaterial:editBC') && editRecord.materialId === record.materialId">
							<a @click="handleSaveEdit">保存</a>
							<a class="text-danger hover:text-danger" @click="handleCancelEdit">取消</a>
						</template>
						<template v-else>
							<a @click="handleEdit(record)" v-if="hasPerm('emsOrderMaterial:editBC')">编辑</a>
						</template>
						<a @click="$refs.outDetail.show(record)">出库记录</a>
					</a-space>
				</span>
			</s-table>

			<add-form ref="addForm" @ok="handleOk" />
			<out-detail ref="outDetail" />
		</a-card>
	</a-modal>
</template>

<script lang="ts">
import { Component, Vue, Ref } from "vue-property-decorator";
import { STable } from '@/components'
import { page } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import {
	addOutOrderForProductionOrder,
	deleteBatchBCMaterial,
	editBCMaterial
} from '@/api/modular/main/emsorder/emsOrderManage'
import addForm from '@/views/main/emsordermaterial/emsOrderMaterialAddFormOutOrder.vue'
import outDetail from '@/views/main/packingStorehouse/outedProductionOrder/outDetail.vue'
import { debounce } from 'xijs';

import { page as teamPage } from '@/api/modular/main/classGroup/classGroup'

type Record = {
	orderMaterialId: string,
	materialId: string,
	materialCode: string,
	materialName: string,
	number: number,
	completedNumber: number,

}

type EmsOrder = {
	orderId: string,
	orderNumber: string,
}


@Component({
	components: {
		STable,
		addForm,
		outDetail,
	}
})

export default class OutStoreEditForm extends Vue {
	@Ref() readonly table!: any

	visible = false
	title = ''
	editRecord: Partial<Record> = {}

	// 高级搜索 展开/关闭
	advanced = false
	// 查询参数
	queryParam = {
		materialType: '',
		orderId: '',
		pageSize: 10,
		classGroupId: undefined,
		materialCode: '',
	}
	teamList = [];
	//获取领用方
	getTeamList() {
		teamPage({
			pageSize: -1,
			status: 0
		}).then(res => {
			this.teamList = res.data.rows;
		})
	}
	columns = [
		{
			align: 'center',
			title: '序号', width: '80px',
			dataIndex: '',
			customRender(text: any, record: Record, index: number) {
				return `${index + 1}`
			}
		},
		{
			align: 'center',

			title: '包材编号',
			dataIndex: 'materialCode'
		},
		{
			align: 'center',

			title: '包材名称',
			dataIndex: 'materialName',
		},
		{
			align: 'center',

			title: '需求数量',
			dataIndex: 'number',
			scopedSlots: { customRender: 'number' }

		},
		{
			align: 'center',

			title: '已出库数量',
			dataIndex: 'completedNumber'
		},
		{
			align: 'center',

			title: '待出库数量',
			dataIndex: '',
			customRender(text: any, record: Record, index: number) {
				return `${record.number - record.completedNumber}`
			}
		},
		{
			width: '180px',

			title: '领用方',
			dataIndex: 'classGroupId',
			scopedSlots: { customRender: 'classGroupId' }
		},
		{
			align: 'center',

			title: '本次出库数量',
			dataIndex: 'normalNumber',
			scopedSlots: { customRender: 'normalNumber' }
		},
		{
			align: 'center',
			title: '操作',
			dataIndex: 'action',
			width: '180px',
			scopedSlots: { customRender: 'action' }
		}
	]

	extra = {}

	selectedRowKeys = []
	selectedRows = []

	confirmLoading = false
	emsOrder: Partial<EmsOrder> = {}
	materialType = this.$businessEnum.MATERIAL_TYPE_ENUM.packing.id

	rowSelection = {
		getCheckboxProps: (record: Record) => {
			console.log(record.completedNumber)

			return {
				props: {
					disabled: record.completedNumber > 0,
					name: record.materialCode,
				},
			}
		},
		selectedRowKeys: this.selectedRowKeys,
		onChange: this.onSelectChange
	}

	//导出
	handleExport() {
		let emsOrder = this.emsOrder
		let $data = this.table.$data
		$data = $data.localDataSource

		let filterData = $data
		let orderMaterialFullResultList = filterData.map(value => {
			return Object.assign({}, value, {
				sourceOrderId: emsOrder.orderId,
				sourceOrderMaterialId: value.orderMaterialId,
				// number: value.normalNumber,
				extraNumber: value.extraNumber,
			})
		})

		let orderBean = {
			orderId: '',
			sourceOrderId: emsOrder.orderId,
			orderParentId: '',
			orderPids: '',
			orderNumber: '',
			orderType: this.$businessEnum.ORDER_TYPE_ENUM.outOrder.id,
			orgId: '',
			targetOrgId: '',
			isOverseasStore: '',
			countryCode: '',
			file: '',
			remark: '',
			executeStatus: '',
			executeProgress: '',
			issueTime: '',
			estimateCompletionTime: '',
			receiveTime: '',
			status: '',
			createTime: '',
			createUser: '',
			updateTime: '',
			updateUser: '',
			orderMaterialFullResultList: orderMaterialFullResultList,
		}
		console.log(orderBean);
		this.dwnLoading = true
		Vue.prototype.download("/emsOrderMaterial/scckExport", orderBean, `领料单_${Vue.prototype.dayjs(new Date()).format('YYYY/MM/DD HH:mm:ss')}.xls`, null, true).then(res => {
			this.dwnLoading = false
		})
	}
	dwnLoading = false
	// 加载数据方法 必须为 Promise 对象
	getData(parameter: { pageNo: number, pageSize: number }) {
		this.queryParam.materialType = this.materialType
		this.queryParam.orderId = this.emsOrder?.orderId as string
		this.queryParam.pageSize = -1
		return page(Object.assign(parameter, this.queryParam)).then((res) => {
			res.data.rows.forEach(value => {
				value.normalNumber = value.number - value.completedNumber
			})
			return res.data
		})
	}

	show(record: EmsOrder) {
		console.log('$store', this.$store)
		this.visible = true
		this.emsOrder = record
		this.queryParam = {
			materialType: '',
			orderId: '',
			pageSize: 10,
			classGroupId: undefined,
			materialCode: '',
		};
		this.title = `出库（${record.orderNumber}）`
		setTimeout(() => {
			this.handleOk()
		}, 100)
		this.getTeamList();
	}

	handleEdit(record: Record) {
		console.log("record", record);
		this.editRecord = Object.assign({}, record)
	}

	handleSaveEdit = debounce(this.saveEdit, 1000)

	saveEdit() {
		const params = {
			orderMaterialId: this.editRecord?.orderMaterialId,
			number: this.editRecord?.number
		}
		editBCMaterial(params).then((res) => {
			console.log(res)
			//@ts-ignore
			if ((res).success) {
				this.$message.success('编辑成功')
				this.handleOk()
			} else {
				//@ts-ignore
				this.$message.info('编辑失败：' + res.message)
			}
		}).finally(() => {
			this.editRecord = {}

		})
	}


	handleCancelEdit() {
		this.editRecord = {}
	}


	handleOk() {
		this.table.refresh()
	}

	onSelectChange(selectedRowKeys, selectedRows) {
		console.log(selectedRowKeys, selectedRows)
		this.selectedRowKeys = selectedRowKeys
		this.selectedRows = selectedRows
	}


	handleRemove() {
		if (!this.selectedRowKeys.length) {
			return this.$message.info("请选择包材")
		}
		this.$confirm({
			title: '系统提示',
			content: '是否确认删除？',
			onOk: () => {
				const params = {
					orderId: this.emsOrder?.orderId,
					orderMaterialIds: this.selectedRows.map(item => item.orderMaterialId)
				}
				deleteBatchBCMaterial(params).then(res => {
					console.log(res)
					//@ts-ignore
					if ((res).success) {
						this.$message.success('删除成功')
						this.handleOk()
					} else {
						//@ts-ignore
						this.$message.info('删除失败：' + res.message)
					}
				})
			},
			onCancel() {
				console.log('Cancel');
			},
		});

	}


	handleSubmit() {
		let emsOrder = this.emsOrder
		let $data = this.table.$data
		$data = $data.localDataSource

		let filterData = $data.filter(value => value.normalNumber > 0 || value.extraNumber > 0)
		if (filterData.length == 0) {
			this.$message.error('请先填写物料的数量')
			return
		}
		this.$confirm({
			title: '系统提示',
			content: '是否确认出库？',
			onOk: () => {

				let orderMaterials = filterData.map(value => {
					return Object.assign({}, value, {
						sourceOrderId: emsOrder.orderId,
						sourceOrderMaterialId: value.orderMaterialId,
						number: value.normalNumber,
						extraNumber: value.extraNumber,
					})
				})

				let orderBean = {
					orderId: '',
					sourceOrderId: emsOrder.orderId,
					orderParentId: '',
					orderPids: '',
					orderNumber: '',
					orderType: this.$businessEnum.ORDER_TYPE_ENUM.outOrder.id,
					orgId: '',
					targetOrgId: '',
					isOverseasStore: '',
					countryCode: '',
					file: '',
					remark: '',
					executeStatus: '',
					executeProgress: '',
					issueTime: '',
					estimateCompletionTime: '',
					receiveTime: '',
					status: '',
					createTime: '',
					createUser: '',
					updateTime: '',
					updateUser: '',
					orderMaterials: orderMaterials,
				}
				addOutOrderForProductionOrder(orderBean).then(res => {
					//@ts-ignore
					if (res.success) {
						this.$message.info('出库成功')
						this.$emit("ok")
						this.handleCancel()
					} else {
						//@ts-ignore
						this.$message.error('出库失败：' + res.message)
					}
				})

			},
			onCancel() {
				console.log('Cancel');
			},
		});

	}

	handleCancel() {
		this.visible = false;
	}

}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
